<template>
	<div>
		<div class="nameDiv">
			<span>申报政策：</span>
			<span class="policyName" @click="$router.push({path: 'policyDetail', query: {id: policy.policy.id}})">{{policy.policy.name}}</span>
		</div>
		<div class="underLine"></div>
		<div class="formDiv">
			<el-form ref="form" :model="sendMsg" :rules="rules" label-width="120px" class="form">
				<el-form-item label="申报理由：" prop="reason">
					<el-input type="textarea" resize="none" v-model.trim="sendMsg.reason" placeholder="请输入申报理由：" :autosize="{minRows: 4, maxRows: 4}" maxLength="200"></el-input>
				</el-form-item>
				<el-form-item label="上传申报材料：" prop="files">
					<div style="text-align: left">
						<el-button class="uploadBtn" icon="el-icon-upload" @click="selectFile()">上传文件</el-button>
						<div style="display: flex; align-items: center" v-for="(file, index) in sendMsg.files" :key="index">
							<span>{{file.name}}</span>
							<i class="el-icon-close deleteBtn" @click="deleteFile(index)"></i>
						</div>
						<input type="file" accept=".rar, .zip, .doc, .docx, .pdf, .xls, .xlsx, .jpg, .png" ref="fileInput" v-show="false" @change="changeFile"></input>
						<div style="color: #999999">文件大小不超过30M，支持扩展名：.rar .zip .doc .docx .pdf .xls .xlsx .jpg .png</div>
					</div>
				</el-form-item>
				<el-form-item label="">
          <Buttons :buttons="buttons" @sendPolicy="sendPolicy" @none="''" class="btns"></Buttons>
				</el-form-item>
			</el-form>
		</div>
		<MaskCover :title="'提交中，请稍等...'" v-show="sending"></MaskCover>
	</div>
</template>

<script>
	import MaskCover from '@/components/maskCover'

	import {request, uploadFile} from '@/utils/request.js'
	import config from '@/utils/config.js'
	import {checkLogin, confirmEnding, formatSendBtn} from '@/utils/util.js'

  import apply from '@/formRules/policy/apply.js'

  import { getPolicy } from '@/common/api/company.js'

	export default {
		name: "policySend",
		components: {MaskCover},
    mixins: [apply],
    computed:{
      buttons(){
        if(this.policy.applyRedemptionInfo.applyStatus == 4){
          return [{ text: "立即申报", type: "success", size: "l", method: "sendPolicy" }]
        } else {
          return [{ text: "已申报", type: "weakSuccess", size: "l", method: "none", disabled:true }]
        }
      }
    },
		data() {
			return {
				policy: {
					applyRedemptionInfo:{},
					policy: {
						applyStatus: 4,
						name: '',
						id: ''
					}
				},
        totalSize : 0,
				sending: false,
			}
		},
		methods: {
			/**
			 * 返回上一页
			 */
			goBack() {
				this.$router.go(-1)
			},
			/**
			 * 获取政策信息
			 */
			getPolicy() {
				let ns = this
				ns.sendMsg.applyId = ns.$route.query.applyId
				ns.policy.policy.name = ns.$route.query.name
				ns.policy.policy.id = ns.$route.query.policyId
        getPolicy(ns.$route.query.policyId).then(res => {
          ns.policy = res.data
        })
			},
			/**
			 * 选择文件事件
			 */
			selectFile() {
				this.$refs.fileInput.click()
			},
			/**
			 * 删除文件
			 */
			deleteFile(index) {
				let ns = this
				let fileList = []
				for(let i = 0; i < ns.sendMsg.files.length; i++) {
					if(i != index) {
						fileList.push(ns.sendMsg.files[i])
					}else{
						// 把全局的总计大小减去
						this.totalSize -= parseInt(ns.sendMsg.files[i].size) 
					}
				}
				ns.sendMsg.files = fileList
			},
			/**
			 * 完成选择文件事件
			 */
			changeFile(e) {
				let ns = this
				let file = e.target.files[0]
				if(file == undefined) {
					return
				}
				// 检测文件大小是否过大
				this.totalSize += parseInt(file.size) 
				console.log("this.totalSize",this.totalSize)
				if(file.size / 1048576 >= 30 || this.totalSize / 1048576 >= 30) { // 原为50MB,10-12改为30MB
					this.totalSize -= parseInt(file.size) 
					ns.$message.error('文件合计大小不能超过30MB')
					return
				}
				if(!confirmEnding(file.name, [
					'.rar',
					'.zip',
					'.doc',
					'.docx',
					'.pdf',
					'.jpg',
					'.xls', 
					'.xlsx', 
					'.png'
					])) {
					ns.$message.error('文件格式不正确')
					return
				}
				ns.sendMsg.files.push(file)
        this.$refs['form'].validateField('files')
			},
			/**
			 * 申报政策
			 */
			sendPolicy () {
        this.$refs['form'].validate(async valid => {
          if(valid) {
            let ns = this
            ns.sending = true
            let formData = new FormData()
            for(let i = 0; i < ns.sendMsg.files.length; i++) {
              formData.append('files', ns.sendMsg.files[i])
            }
            formData.append('applyId', ns.sendMsg.applyId)
            formData.append('reason', ns.sendMsg.reason)
            uploadFile(ns, config.api.policyApplyAddItemAgain, formData).then(function (res) {
              ns.sending = false
              if(res.code == 200) {
                ns.$message.success('申报成功')
                ns.getPolicy()
                // 恢复初始状态,销毁已有数据
                ns.sendMsg = {
                  applyId: null,
                  reason: '',
                  files: []
                },
                ns.$router.replace({ name: 'companySend' }); //返回列表页
              } else {
                ns.$message.error(res.msg)
              }
            })
          }
        })
			},
			/**
			 * 格式化显示按钮颜色
			 */
			formatBtn (policy) {
				return formatSendBtn(policy)
			}
		},
		mounted() {
			let ns = this
			if(checkLogin(ns)) {
				ns.getPolicy()
			}
		},
		activated() {
			let ns = this
			if(checkLogin(ns)) {
				ns.getPolicy()
			}
		}
	}
</script>

<style scoped>
  .btns{
    justify-content: left !important;
  }

	.breadcrumb {
		width: 1000px;
		margin: 20px 0;
	}

	.backBtn {
		border: 1px solid #eeeeee;
		white-space: nowrap;
		font-size: 12px;
		height: 30px;
		width: 70px;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 3px;
	}

	.backBtn:hover {
		cursor: pointer;
		box-shadow: 0px 0px 5px #EEEEEE;
	}

	.roomDiv {
		display: flex;
		justify-content: center;
		margin-top: 20px;
	}

	.roomDiv .leftDiv {
		width: 200px;
		text-align: left;
	}

	.roomDiv .rightDiv {
		width: 800px;
		margin-left: 30px;
	}

	.titleDiv {
		border-bottom: 2px solid #045db9;
		text-align: left;
		padding: 10px;
		font-size: 20px;
		font-weight: bold;
		color: #045db9;
		margin-bottom: 20px;
	}

	.roomDiv .rightDiv .nameDiv {
		font-weight: bold;
		font-size: 20px;
		margin-bottom: 20px;
	}
	.roomDiv .rightDiv .nameDiv .policyName {
		color: #045db9
	}

	.roomDiv .rightDiv .nameDiv .policyName:hover {
		cursor: pointer;
		text-decoration: underline;
	}

	.roomDiv .rightDiv .statusDiv {
		font-size: 14px;
		color: #999999;
	}

	.roomDiv .rightDiv .formDiv {
		width: 800px;
		margin: 0 auto;
		padding: 30px 0;
	}

	.roomDiv .rightDiv .formDiv .uploadBtn {
		background-color: #f1f2f4;
		color: #045db9;
		border-width: 0;
	}

	.roomDiv .rightDiv .formDiv .sendBtn {
		padding: 0 20px;
		background-color: #045db9;
		display: inline-block;
		color: #FFFFFF;
		border-radius: 5px;
	}

	.roomDiv .rightDiv .formDiv .sendBtn:hover {
		box-shadow: 0px 5px 5px #e1e1e1;
		transition: all 0.2s ease 0s;
		cursor: pointer;
	}

	.roomDiv .rightDiv  .formDiv .deleteBtn {
		font-size: 20px;
		color: #d00000;
		font-weight: bold;
		margin-left: 10px;
	}

	.roomDiv .rightDiv  .formDiv .deleteBtn:hover {
		cursor: pointer;
	}

	.layout {
		min-height: 100vh;
		position: relative;
		padding-bottom: 150px;
		box-sizing: border-box;
	}

	.footer {
		position: absolute;
		bottom: 0;
		width: 100%;
	}
</style>
